package verifycode

import (
	"gohub/pkg/app"
	"gohub/pkg/config"
	"gohub/pkg/redis"
	"time"
)

// 实现 verifycode.Store interface
type RedisStore struct {
	Client    *redis.RedisClient
	KeyPrefix string
}

// Set 实现 verifycode.Store interface 的 Set 方法
func (s *RedisStore) Set(key, val string) bool {
	expired := time.Minute * time.Duration(config.GetInt64("verifycode.expire_time"))

	if app.IsLocal() {
		expired = time.Minute * time.Duration(config.GetInt64("verifycode.debug_expire_time"))
	}

	return s.Client.Set(s.KeyPrefix+key, val, expired)
}

// Get 实现 verifycode.Store interface 的 Get 方法
func (s *RedisStore) Get(key string, clear bool) (val string) {
	key = s.KeyPrefix + key

	val = s.Client.Get(key)
	if clear {
		s.Client.Del(key)
	}

	return val
}

// Verify 实现 verifycode.Store interface 的 Verify 方法
func (s *RedisStore) Verify(key, answer string, clear bool) bool {
	return s.Get(key, clear) == answer
}